<template>
  <div class="order-list">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="orderList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="订单ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="username" label="用户" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleUpdateStatus(scope.row)"
              :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled'"
            >
              更新状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{ currentOrder.username }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ currentOrder.amount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentOrder.updatedAt }}</el-descriptions-item>
      </el-descriptions>
      
      <el-table :data="orderItems" style="width: 100%; margin-top: 20px;" border>
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="subtotal" label="小计" width="100">
          <template #default="scope">
            ¥{{ scope.row.price * scope.row.quantity }}
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新订单状态"
      width="400px"
    >
      <el-form
        ref="statusFormRef"
        :model="statusForm"
        :rules="statusFormRules"
        label-width="80px"
      >
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveStatus" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderStore } from '@/stores'

// 使用订单store
const orderStore = useOrderStore()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  username: '',
  status: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => orderStore.total)
})

// 订单列表（从store中获取）
const orderList = computed(() => orderStore.orderList)
const loading = computed(() => orderStore.loading)

// 详情对话框
const detailDialogVisible = ref(false)

// 状态对话框
const statusDialogVisible = ref(false)
const saveLoading = ref(false)
const statusFormRef = ref()

// 当前选中的订单
const currentOrder = reactive({
  id: null,
  orderNo: '',
  username: '',
  amount: 0,
  paymentMethod: '',
  status: '',
  createdAt: '',
  updatedAt: ''
})

// 订单项
const orderItems = ref([])

// 状态表单
const statusForm = reactive({
  status: ''
})

// 状态表单验证规则
const statusFormRules = {
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'pending':
      return 'info'
    case 'paid':
      return 'primary'
    case 'shipped':
      return 'warning'
    case 'completed':
      return 'success'
    case 'cancelled':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待支付'
    case 'paid':
      return '已支付'
    case 'shipped':
      return '已发货'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    default:
      return '未知'
  }
}

// 获取订单列表
const fetchOrderList = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    orderNo: searchForm.orderNo,
    username: searchForm.username,
    status: searchForm.status,
    dateRange: searchForm.dateRange
  }
  
  try {
    await orderStore.fetchOrderList(params)
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchOrderList()
}

// 处理重置
const handleReset = () => {
  searchForm.orderNo = ''
  searchForm.username = ''
  searchForm.status = ''
  searchForm.dateRange = []
  pagination.currentPage = 1
  fetchOrderList()
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 处理查看订单详情
const handleView = async (row) => {
  try {
    // 获取订单详情
    const orderDetail = await orderStore.getOrderDetail(row.id)
    
    // 填充当前订单信息
    Object.assign(currentOrder, orderDetail)
    
    // 获取订单项
    orderItems.value = orderDetail.items || []
    
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 处理更新状态
const handleUpdateStatus = (row) => {
  // 填充当前订单信息
  Object.assign(currentOrder, row)
  
  // 设置状态表单默认值
  statusForm.status = row.status
  
  statusDialogVisible.value = true
}

// 处理保存状态
const handleSaveStatus = () => {
  if (!statusFormRef.value) return
  
  statusFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        await orderStore.updateOrderStatus(currentOrder.id, statusForm.status)
        ElMessage.success('状态更新成功')
        statusDialogVisible.value = false
        
        // 重新获取订单列表以更新状态
        await fetchOrderList()
      } catch (error) {
        ElMessage.error('状态更新失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchOrderList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchOrderList()
}

// 组件挂载后获取订单列表
onMounted(() => {
  fetchOrderList()
})
</script>

<style lang="scss" scoped>
.order-list {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>